package com.vm.osm.business.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.JsonObject;
import com.vm.osm.business.dao.*;
import com.vm.osm.business.dto.CreateNotifyReq;
import com.vm.osm.business.dto.req.failOrder.ReqAddFailOrder;
import com.vm.osm.business.dto.req.failOrder.ReqDispatchFail;
import com.vm.osm.business.dto.req.failOrder.ReqSearchFailureOrder;
import com.vm.osm.business.dto.rsp.checkPlan.PlanContent;
import com.vm.osm.business.dto.rsp.checkPlan.RspPlanContentPage;
import com.vm.osm.business.dto.rsp.failOrder.*;
import com.vm.osm.business.dto.rsp.orderInst.Maintenance;
import com.vm.osm.business.dto.rsp.orderInst.RspMaintenancePage;
import com.vm.osm.business.entity.OsmFailureType;
import com.vm.osm.business.entity.OsmOrderFailure;
import com.vm.osm.business.entity.OsmOrderFeeInfo;
import com.vm.osm.business.entity.OsmOrderFlow;
import com.vm.osm.business.service.IOrderFailureService;
import com.vm.osm.business.service.IOsmDispatchRuleService;
import com.vm.osm.business.service.IOsmIndexConfigService;
import com.vm.osm.business.service.IOsmSysConfigService;
import com.vm.osm.business.util.GsonUtil;
import com.vm.osm.business.util.NotifyUtil;
import com.vm.osm.business.util.UserDataUtil;
import com.vm.osm.business.util.UuidUtil;
import com.vma.eams.spring.boot.log.LogCollector;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by chenzui on 2018/3/13.
 */
@Service
public class OrderFailServiceImpl implements IOrderFailureService {

    private Logger LOG = Logger.getLogger(this.getClass());
    @Autowired
    private OsmOrderFailureMapper osmOrderFailureMapper;
    @Autowired
    private OsmOrderLogMapper osmOrderLogMapper;
    @Autowired
    private OsmOrderPhotoMapper osmOrderPhotoMapper;
    @Autowired
    private OsmOrderFeeInfoMapper osmOrderFeeInfoMapper;
    @Autowired
    private OsmOrderAccessoryMapper osmOrderAccessoryMapper;
    @Autowired
    private OsmOrderFlowMapper osmOrderFlowMapper;
    @Autowired
    private OsmFailureTypeMapper osmFailureTypeMapper;

    @Autowired
    private IOsmDispatchRuleService osmDispatchRuleService;

    @Autowired
    private IOsmIndexConfigService osmIndexConfigService;

    @Autowired
    private OsmOrderEvaluateMapper osmOrderEvaluateMapper;

    @Autowired
    private NotifyUtil notifyUtil;

    @Override
    public int deleteByPrimaryKey(String id) {
        return osmOrderFailureMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(OsmOrderFailure record) {
        return osmOrderFailureMapper.insertSelective(record);
    }

    @Override
    public int insertSelective(OsmOrderFailure record) {
        return osmOrderFailureMapper.insertSelective(record);
    }

    @Override
    public OsmOrderFailure selectByPrimaryKey(String id) {
        return osmOrderFailureMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(OsmOrderFailure record) {
        return osmOrderFailureMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(OsmOrderFailure record) {
        return osmOrderFailureMapper.updateByPrimaryKey(record);
    }

    @Override
    public RspFailOrderPage queryOrderFailureByCond(ReqSearchFailureOrder reqSearchFailureOrder) {
        RspFailOrderPage  rspFailOrderPage = new RspFailOrderPage();
        Page page = PageHelper.startPage(reqSearchFailureOrder.getPage_num(),reqSearchFailureOrder.getPage_size(),true);
        List<FailOrderPage> dataList = osmOrderFailureMapper.queryOrderFailureByCond(reqSearchFailureOrder);
        rspFailOrderPage.setData_list(dataList);
        rspFailOrderPage.setTotal_num(page.getTotal());
        rspFailOrderPage.setPage_num(page.getPageNum());
        rspFailOrderPage.setPage_size(page.getPageSize());
        return rspFailOrderPage;
    }

    @Override
    public RspFailOrderDetail getOrderFailureById(String id) {
        RspFailOrderDetail detail = osmOrderFailureMapper.queryOrderFailureById(id);
        //查询解决方案
        OrderFailDealLog log =  osmOrderLogMapper.queryLogByOrderId(id);
        //故障单解决图片
        List<OrderSolutionPhoto> photos = osmOrderPhotoMapper.queryPhotosByOrderId(id);

        List<OrderFeeInfo> feeInfos = osmOrderFeeInfoMapper.queryFeeInfosById(id);

        List<OrderAccessoryInfo> accessoryInfos = osmOrderAccessoryMapper.queryAccessoryInfosByOrderId(id);

        List<OrderFlowInfo> flowInfos = osmOrderFlowMapper.queryFlowInfosByOrderId(id);

        detail.setAccessory_infos(accessoryInfos);

        detail.setFee_infos(feeInfos);

        detail.setPhotos(photos);

        detail.setFlow_infos(flowInfos);

        detail.setOrder_fail_deal_log(log);

        detail.setEvaluate(osmOrderEvaluateMapper.queryEvaluateByOrder(id));

        // TODO: 2018/5/5 查询处理人信息


        return detail;
    }

    @Override
    public void handleOrder(String id, String status, String remark,String staffName,String staffId) {
        OsmOrderFailure orderFailure = osmOrderFailureMapper.selectByPrimaryKey(id);

        OsmOrderFlow flow = new OsmOrderFlow();
        flow.setOperateUserName(staffName);
        flow.setOperateUserId(staffId);
        flow.setStatus(new Byte("1"));
        flow.setOrderId(id);
        flow.setCreateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setUpdateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setId(UuidUtil.getRandomUuid());


//        0草稿1审批中2待分配3处理中4处理完成5已完成6已关闭7已退回8故障上报9待受理10撤回
        if("5".equals(status)){
            flow.setSimpleDesc("用户确认完成");
            orderFailure.setStatus("5");
        }else if("7".equals(status)){
            flow.setSimpleDesc("用户退回");
            orderFailure.setStatus("7");
        }else if("10".equals(status)){
            flow.setSimpleDesc("用户撤回");
            orderFailure.setStatus("10");
        }else if("-1".equals("status")){
            osmOrderFailureMapper.deleteByPrimaryKey(id);
            return;
        }
        osmOrderFailureMapper.updateByPrimaryKeySelective(orderFailure);

        osmOrderFlowMapper.insertSelective(flow);
    }

    @Override
    public void dispatchIn(ReqDispatchFail reqDispatchFail) {
        String orderId = reqDispatchFail.getOrder_id();
        OsmOrderFailure orderFailure = osmOrderFailureMapper.selectByPrimaryKey(orderId);
        orderFailure.setModifyTime(new Date());
        orderFailure.setStatus("5");//待接单
        orderFailure.setDispatchTime(new Date());
        orderFailure.setAcceptStaffId(reqDispatchFail.getTarget_staff_id());
        osmOrderFailureMapper.updateByPrimaryKeySelective(orderFailure);


        // TODO: 2018/3/14  记录工单操作历史

        OsmOrderFlow flow = new OsmOrderFlow();
        flow.setCreateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setOperateUserId(reqDispatchFail.getOperate_staff_id());
        flow.setUpdateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setId(UuidUtil.getRandomUuid());
        flow.setOrderId(orderId);
        flow.setStatus(new Byte("1"));
        flow.setOperateUserName(reqDispatchFail.getTarget_staff_name());
        flow.setSimpleDesc(reqDispatchFail.getTarget_staff_name()+"分配了工单"+ (StringUtils.isEmpty(reqDispatchFail.getRemark()) ? "":","+reqDispatchFail.getRemark()));
        osmOrderFlowMapper.insertSelective(flow);

        LogCollector.INSTANCE.put("工单号",orderFailure.getOrderNbr());
//        收到指派工单【工单名称】，快去接单吧
        String content = "收到指派工单【"+orderFailure.getOrderTitle() +"】，快去接单吧";
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("order_type","1");
        jsonObject.addProperty("type","1");
        jsonObject.addProperty("order_id",orderFailure.getId());
        String extra = GsonUtil.toJson(jsonObject);
        String title = "收到派单";
        String sender = reqDispatchFail.getOperate_staff_id();
        String target = reqDispatchFail.getTarget_staff_id();
        CreateNotifyReq createNotifyReq = new CreateNotifyReq(content,extra,title,sender,target,orderFailure.getEnterpriseId());

        notifyUtil.send(createNotifyReq);
    }

    @Override
    public RspFailOrderPage queryOrderFailureByStaffId(Integer pageNum,Integer pageSize,String staffId) {
        RspFailOrderPage  rspFailOrderPage = new RspFailOrderPage();
        Page page = PageHelper.startPage(pageNum,pageSize,true);
        List<FailOrderPage> dataList = osmOrderFailureMapper.queryOrderFailureByStaffId(staffId);
        rspFailOrderPage.setData_list(dataList);
        rspFailOrderPage.setTotal_num(page.getTotal());
        rspFailOrderPage.setPage_num(page.getPageNum());
        rspFailOrderPage.setPage_size(page.getPageSize());
        return rspFailOrderPage;
    }

    @Override
    public OsmOrderFailure get(Map<String, Object> params) {
        return osmOrderFailureMapper.get(params);
    }

    @Override
    public void specialCommit(ReqAddFailOrder reqAddFailOrder, HttpServletRequest request) {
        OsmOrderFailure osmOrderFailure = new OsmOrderFailure();
        if(reqAddFailOrder.getId() != null && !"".equals(reqAddFailOrder.getId())){
            osmOrderFailure = osmOrderFailureMapper.selectByPrimaryKey(reqAddFailOrder.getId());
        }else {
            osmOrderFailure.setId(UuidUtil.getRandomUuid());
            OsmFailureType type = osmFailureTypeMapper.selectByPrimaryKey(reqAddFailOrder.getFailure_type_id());
            String orderNbr = osmIndexConfigService.getIndex(UserDataUtil.getUserSelectedEnterpriseId(request),"GZ"+type.getFailCode());
            osmOrderFailure.setOrderNbr(orderNbr);
        }

        osmOrderFailure.setCreateTime(new Date());
        osmOrderFailure.setAppointmentTime(reqAddFailOrder.getAppointment_time());
        osmOrderFailure.setDescription(reqAddFailOrder.getSimple_desc());
        osmOrderFailure.setDeviceId(reqAddFailOrder.getDevice_id());
        osmOrderFailure.setDeviceName(reqAddFailOrder.getDevice_name());
        osmOrderFailure.setFailTypeId(reqAddFailOrder.getFailure_type_id());
        osmOrderFailure.setFileUrls(reqAddFailOrder.getFile_urls());
        osmOrderFailure.setPhotoUrls(reqAddFailOrder.getPhoto_urls());
        osmOrderFailure.setLinkMan(reqAddFailOrder.getLink_man());
        osmOrderFailure.setLinkPhone(reqAddFailOrder.getLink_phone());
        osmOrderFailure.setSubmitStaffId(UserDataUtil.getStaffId(request));
        osmOrderFailure.setDeviceTypeId(reqAddFailOrder.getDevice_type_id());
        osmOrderFailure.setSubmitStaffName(UserDataUtil.getStaffName(request));
        osmOrderFailure.setEnterpriseId(UserDataUtil.getUserSelectedEnterpriseId(request));
        osmOrderFailure.setDepartmentId(UserDataUtil.getDepartmentId(request));
        osmOrderFailure.setCompanyId(reqAddFailOrder.getCompany_id());
        osmOrderFailure.setCompanyName(reqAddFailOrder.getCompany_name());
        osmOrderFailure.setPriorityDesc(reqAddFailOrder.getPriority_desc());
        osmOrderFailure.setOrderTitle(reqAddFailOrder.getFailure_title());

        osmOrderFailure.setLocation(reqAddFailOrder.getLocation());
        if(reqAddFailOrder.getStatus().equals("1")){
            osmOrderFailure.setStatus("3");// TODO: 2018/3/13 直接设置为待分派
        }else {
            osmOrderFailure.setStatus("0");
        }
        osmOrderFailure.setModifyTime(new Date());
        osmOrderFailure.setPriorityId(reqAddFailOrder.getPriority_id());
        osmOrderFailureMapper.insert(osmOrderFailure);

        // TODO: 2018/3/14  记录工单操作历史

        OsmOrderFlow flow = new OsmOrderFlow();
        flow.setCreateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setOperateUserId(UserDataUtil.getStaffId(request));
        flow.setUpdateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setId(UuidUtil.getRandomUuid());
        flow.setOrderId(osmOrderFailure.getId());
        flow.setStatus(new Byte("1"));
        flow.setOperateUserName(UserDataUtil.getStaffName(request));
        flow.setSimpleDesc(UserDataUtil.getStaffName(request)+"提交了工单");
        osmOrderFlowMapper.insertSelective(flow);

        LOG.info("调用自动派单逻辑");
        if(!osmOrderFailure.getStatus().equals("0")){
            osmDispatchRuleService.orderAutoDispatch(osmOrderFailure.getId());
        }
        LogCollector.INSTANCE.put("工单号",osmOrderFailure.getOrderNbr());

    }

    @Override
    public RspMaintenancePage queryOrderByDeviceId(Integer pageNum, Integer pageSize, String deviceId) {
        RspMaintenancePage rspMaintenancePage = new RspMaintenancePage();
        Page page = PageHelper.startPage(pageNum,pageSize,true);
        List<Maintenance> list = osmOrderFailureMapper.queryOrderByDeviceId(deviceId);
        rspMaintenancePage.setData_list(list);
        rspMaintenancePage.setPage_num(page.getPageNum());
        rspMaintenancePage.setPage_size(page.getPageSize());
        rspMaintenancePage.setTotal_num(page.getTotal());
        return rspMaintenancePage;
    }

    @Override
    public String commit(ReqAddFailOrder reqAddFailOrder, HttpServletRequest request) {
        OsmOrderFailure osmOrderFailure = new OsmOrderFailure();
        if(reqAddFailOrder.getId() != null && !"".equals(reqAddFailOrder.getId())){
            osmOrderFailure = osmOrderFailureMapper.selectByPrimaryKey(reqAddFailOrder.getId());
        }else {
            osmOrderFailure.setId(UuidUtil.getRandomUuid());
            OsmFailureType type = osmFailureTypeMapper.selectByPrimaryKey(reqAddFailOrder.getFailure_type_id());
            String orderNbr = osmIndexConfigService.getIndex(UserDataUtil.getUserSelectedEnterpriseId(request),"GZ"+type.getFailCode());
            osmOrderFailure.setOrderNbr(orderNbr);
        }

        osmOrderFailure.setCreateTime(new Date());
        osmOrderFailure.setAppointmentTime(reqAddFailOrder.getAppointment_time());
        osmOrderFailure.setDescription(reqAddFailOrder.getSimple_desc());
        osmOrderFailure.setDeviceId(reqAddFailOrder.getDevice_id());
        osmOrderFailure.setDeviceName(reqAddFailOrder.getDevice_name());
        osmOrderFailure.setFailTypeId(reqAddFailOrder.getFailure_type_id());
        osmOrderFailure.setFileUrls(reqAddFailOrder.getFile_urls());
        osmOrderFailure.setPhotoUrls(reqAddFailOrder.getPhoto_urls());
        osmOrderFailure.setLinkMan(reqAddFailOrder.getLink_man());
        osmOrderFailure.setLinkPhone(reqAddFailOrder.getLink_phone());
        osmOrderFailure.setPriorityDesc(reqAddFailOrder.getPriority_desc());
        String staffId = UserDataUtil.getStaffId(request);
        String staffName = UserDataUtil.getStaffName(request);
        osmOrderFailure.setDepartmentId(UserDataUtil.getDepartmentId(request));
        osmOrderFailure.setSubmitStaffId(staffId);
        osmOrderFailure.setDeviceTypeId(reqAddFailOrder.getDevice_type_id());
        osmOrderFailure.setSubmitStaffName(staffName);
        osmOrderFailure.setLocationX(reqAddFailOrder.getLocation_x());
        osmOrderFailure.setLocationY(reqAddFailOrder.getLocation_y());

        osmOrderFailure.setOrderTitle(reqAddFailOrder.getFailure_title());
        osmOrderFailure.setLocation(reqAddFailOrder.getLocation());
        if(reqAddFailOrder.getStatus().equals("1")){
            osmOrderFailure.setStatus("3");// TODO: 2018/3/13 直接设置为待分派
        }else {
            osmOrderFailure.setStatus("0");
        }
        osmOrderFailure.setModifyTime(new Date());
        osmOrderFailure.setPriorityId(reqAddFailOrder.getPriority_id());
        osmOrderFailure.setEnterpriseId(UserDataUtil.getUserSelectedEnterpriseId(request));
        osmOrderFailureMapper.insert(osmOrderFailure);

        // TODO: 2018/3/14  记录工单操作历史

        OsmOrderFlow flow = new OsmOrderFlow();
        flow.setCreateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setOperateUserId(staffId);
        flow.setUpdateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setId(UuidUtil.getRandomUuid());
        flow.setOrderId(osmOrderFailure.getId());
        flow.setStatus(new Byte("1"));
        flow.setOperateUserName(staffName);
        flow.setSimpleDesc("提交了工单");
        osmOrderFlowMapper.insertSelective(flow);

        LOG.info("调用自动派单逻辑");
        if(!osmOrderFailure.getStatus().equals("0")){
            osmDispatchRuleService.orderAutoDispatch(osmOrderFailure.getId());
        }
        LogCollector.INSTANCE.put("故障",osmOrderFailure.getOrderNbr());
        return osmOrderFailure.getId();
    }
}
